import React, { Component } from 'react'
import {formatDate} from '../../utils/defaultDate.js'
import {reqWeather} from '../../api'
import  memoryUtils from '../../utils/memoryUtils.js'
import {withRouter} from 'react-router-dom'
import menulist from '../left_nav/menulist.js'
import {Modal } from 'antd'
import  storeUtils from '../../utils/storeUtils.js'
import LinkButton from '../link-button'
import './index.less'


const { confirm } = Modal;
 class Header extends Component {
    state={
        date:formatDate(Date.now()),
        dayPictureUrl:'',
        weather:''
    }

   async componentDidMount(){
     const {dayPictureUrl, weather} = await reqWeather('南京')

     this.setState({
        dayPictureUrl,
        weather,
     })
      }


    getBreadeTitle=()=>{
        const pathname = this.props.location.pathname;
        let title;
        menulist.forEach(item=>{
            if(item.key===pathname){
                title=item.title
            }else if(item.children){
               const res = item.children.find(i=>pathname.indexOf(i.key)===0)

                   if(res){
                       title = res.title
                   }
                
            }
        })
   
     return title
    }

    logout=()=>{
        confirm({

            content: '您确定退出吗',
            onOk:()=> {
                storeUtils.removeUser()
                memoryUtils.user={}
                this.props.history.replace('/login') 
         
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }
    

    render() {
        const{date,dayPictureUrl,weather} = this.state
        return (
            <div className="headerContiner">
                <div className='header-top'>
                <span>欢迎，{memoryUtils.user.username}</span>
                {/* <a href="javascript:;" onClick = {this.logout}>退出</a> */}
                <LinkButton onClick = {this.logout}>退出</LinkButton>

                </div>
                <div className='header-bottom'>
                  <div className='header-bottom-left'>{this.getBreadeTitle()}</div>
                  <div className="header-bottom-right">
                    <span>{date}</span>
                    <img src={dayPictureUrl} />
                    <span>{weather}</span>
                  </div>
                
                </div>
            </div>
        )
    }
}

export default withRouter(Header)
